package com.cskaoyan.service;

import com.cskaoyan.bean.cart.*;
import com.cskaoyan.bean.domain.*;
import com.cskaoyan.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    GrouponRulesMapper grouponRulesMapper;

    @Autowired
    CartMapper mapper;

    @Autowired
    CouponUserMapper couponUserMapper;

    @Autowired
    CartMapper cartMapper;

    @Autowired
    AddressMapper addressMapper;

    @Autowired
    CouponMapper couponMapper;

    @Autowired
    GoodsProductMapper goodsProductMapper;

    @Override
    public CartIndexVO getIndex(Integer userId) {
        CartExample example = new CartExample();
        CartExample.Criteria criteria = example.createCriteria();
        //没有被删除的
        criteria.andDeletedEqualTo(false);
        //根据用户id找到对应的购物车
        criteria.andUserIdEqualTo(userId);

        List<Cart> cartList = mapper.selectByExample(example);

        //amount是总金额，count是数量
        BigDecimal checkedGoodsAmount = new BigDecimal("0");
        Short checkedGoodsCount = new Short("0");
        BigDecimal goodsAmount = new BigDecimal("0");
        Short goodsCount = new Short("0");

        //判断购物车是否为空
        if (!cartList.isEmpty()) {
            for (Cart goods : cartList) {
                //如果被勾选了的
                if (goods.getChecked()) {
                    //数量
                    int count1 = checkedGoodsCount + goods.getNumber();
                    String s1 = String.valueOf(count1);
                    checkedGoodsCount = new Short(s1);

                    //总金额
                    //先得出数量的bd类型
                    String numberShort1 = String.valueOf(goods.getNumber());
                    BigDecimal numberBigDecimal1 = new BigDecimal(numberShort1);

                    //再算出该商品总价的bd类型（乘法）
                    BigDecimal amountBigDecimal1 = goods.getPrice().multiply(numberBigDecimal1);

                    checkedGoodsAmount = amountBigDecimal1.add(checkedGoodsAmount);

                }
                //数量
                int count2 = goodsCount + goods.getNumber();
                String s2 = String.valueOf(count2);
                goodsCount = new Short(s2);

                //总金额
                //先得出数量的bd类型
                String numberShort2 = String.valueOf(goods.getNumber());
                BigDecimal numberBigDecimal2 = new BigDecimal(numberShort2);

                //再算出该商品总价的bd类型（乘法）
                BigDecimal amountBigDecimal2 = goods.getPrice().multiply(numberBigDecimal2);

                goodsAmount = amountBigDecimal2.add(goodsAmount);
            }


        }
        CartTotalVO cartTotalVO = new CartTotalVO();
        cartTotalVO.setCheckedGoodsAmount(checkedGoodsAmount);
        cartTotalVO.setCheckedGoodsCount(checkedGoodsCount);
        cartTotalVO.setGoodsAmount(goodsAmount);
        cartTotalVO.setGoodsCount(goodsCount);

        CartIndexVO cartIndexVO = new CartIndexVO();
        cartIndexVO.setCartList(cartList);
        cartIndexVO.setCartTotal(cartTotalVO);
        return cartIndexVO;

    }

    @Override
    public CartIndexVO checked(CartCheckedBO cartCheckedBO, Integer userId) {
        Integer isChecked = cartCheckedBO.getIsChecked();
        Boolean booleanChecked = false;

        if (isChecked == 1) {
            booleanChecked = true;
        }
        if (isChecked == 0) {
            booleanChecked = false;
        }
        List<Integer> productIds = cartCheckedBO.getProductIds();

        //准备好record和example
        Cart cart = new Cart();
        CartExample example1 = new CartExample();
        CartExample.Criteria criteria = example1.createCriteria();

        for (Integer productId : productIds) {
//            criteria.andCheckedEqualTo(booleanChecked);
            criteria.andProductIdEqualTo(productId);
            criteria.andUserIdEqualTo(userId);
            criteria.andDeletedEqualTo(false);
            cart.setChecked(booleanChecked);

            mapper.updateByExampleSelective(cart, example1);
            example1.clear();
        }

        CartIndexVO cartIndexVO = getIndex(userId);
        return cartIndexVO;

    }

    @Override
    public void update(UpdateBO updateBO, Integer userId) {
        CartExample example = new CartExample();
        CartExample.Criteria criteria = example.createCriteria();

        Integer id = updateBO.getId();
        criteria.andUserIdEqualTo(userId);
        criteria.andIdEqualTo(id);
        criteria.andDeletedEqualTo(false);

        Cart cart = new Cart();
        cart.setGoodsId(updateBO.getGoodsId());
        cart.setNumber(updateBO.getNumber());
        cart.setProductId(updateBO.getProductId());
        cart.setUpdateTime(new Date());

        mapper.updateByExampleSelective(cart, example);
    }

    @Override
    public Map<String, Object> add(AddBO addBO, Integer userId) {
        Integer goodsId = addBO.getGoodsId();
        Integer productId = addBO.getProductId();
        Short number = addBO.getNumber();

        Map goodsMap = mapper.add1(goodsId);
//        Map productMap = mapper.add2(productId);
        GoodsProduct goodsProduct = goodsProductMapper.selectByPrimaryKey(productId);
        String goodsSn = (String) goodsMap.get("goodsSn");
        String goodsName = (String) goodsMap.get("goodsName");
        BigDecimal price = goodsProduct.getPrice();
//        TODO  Q:不确定是否能返回string数组 A:做了临时调整
        String[] specifications = goodsProduct.getSpecifications();
//        String[] specificationsArray = new String[10];
        String picUrl = goodsProduct.getUrl();

        Cart cart = new Cart();
        Date date = new Date();
        cart.setUserId(userId);
        cart.setGoodsId(goodsId);
        cart.setGoodsSn(goodsSn);
        cart.setGoodsName(goodsName);
        cart.setProductId(productId);
        cart.setPrice(price);
        cart.setNumber(number);
        cart.setSpecifications(specifications);
        cart.setChecked(true);
        cart.setPicUrl(picUrl);
        cart.setAddTime(date);
        cart.setUpdateTime(date);
        cart.setDeleted(false);

        mapper.insertSelective(cart);
        Integer goodsCount = getGoodsCount(userId);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("cartId", cart.getId());
        resultMap.put("goodsCount", goodsCount);
        return resultMap;

    }

    @Override
    public CartIndexVO delete(DeleteBO deleteBO, Integer userId) {
        Integer[] productIds = deleteBO.getProductIds();
        CartExample example = new CartExample();
        CartExample.Criteria criteria = example.createCriteria();
        Cart cart = new Cart();
        for (Integer productId : productIds) {
            criteria.andUserIdEqualTo(userId);
            criteria.andProductIdEqualTo(productId);
            cart.setDeleted(true);
            mapper.updateByExampleSelective(cart, example);
        }

        CartIndexVO cartIndexVO = getIndex(userId);
        return cartIndexVO;

    }

    @Override
    public Integer getGoodsCount(Integer userId) {
        CartExample example = new CartExample();
        CartExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andDeletedEqualTo(false);

        List<Cart> cartList = mapper.selectByExample(example);
        Integer cartCount = 0;
        if (!cartList.isEmpty()) {
            for (Cart goods : cartList) {
                cartCount += goods.getNumber();
            }
        }

        return cartCount;
    }

    @Override
    public Integer fastAdd(AddBO addBO, Integer userId) {
        Map<String, Object> resultMap = add(addBO, userId);

//        Integer goodsId = addBO.getGoodsId();
//        Short number = addBO.getNumber();
//        Integer productId = addBO.getProductId();
//        CartExample example = new CartExample();
//        CartExample.Criteria criteria = example.createCriteria();
//        criteria.andUserIdEqualTo(userId);
//        criteria.andDeletedEqualTo(false);
//        criteria.andGoodsIdEqualTo(goodsId);
//        criteria.andNumberEqualTo(number);
//        criteria.andProductIdEqualTo(productId);
//        example.setOrderByClause("add_time desc");
//        List<Cart> cartList = mapper.selectByExample(example);

        Integer cartId = (Integer) resultMap.get("cartId");

        return cartId;
    }

    @Override
    public CheckoutVO checkout(Integer userId,
                               Integer cartId,
                               Integer addressId,
                               Integer couponId,
                               Integer userCouponId,
                               Integer grouponRulesId) {

        addressId = 1;
        couponId = 2;
        userCouponId = 2;
        grouponRulesId = 2;

        GrouponRules grouponRules = grouponRulesMapper.selectByPrimaryKey(grouponRulesId);
        BigDecimal grouponPrice = grouponRules.getDiscount();
        Address address = addressMapper.selectByPrimaryKey(addressId);
        Coupon coupon = couponMapper.selectByPrimaryKey(couponId);

        BigDecimal couponPrice = coupon.getDiscount();

        CouponUserExample couponUserExample = new CouponUserExample();
        CouponUserExample.Criteria CouponUserCriteria = couponUserExample.createCriteria();
        Date date = new Date();


        CouponUserCriteria.andUserIdEqualTo(userId);
        CouponUserCriteria.andStatusEqualTo((short) 0);
        CouponUserCriteria.andUsedTimeIsNull();
        CouponUserCriteria.andStartTimeLessThanOrEqualTo(date);
        CouponUserCriteria.andEndTimeGreaterThanOrEqualTo(date);
        CouponUserCriteria.andDeletedEqualTo(false);

        Long availableCouponLengthLong = couponUserMapper.countByExample(couponUserExample);

        Integer availableCouponLength = availableCouponLengthLong.intValue();

        //查找选中的购物车商品
        List<Cart> checkedGoodsList = new ArrayList<>();

        if (cartId == 0) {
            //查找选中的购物车商品
            CartExample cartExample = new CartExample();
            CartExample.Criteria cartCriteria = cartExample.createCriteria();
            //没有被删除的
            cartCriteria.andDeletedEqualTo(false);
            //根据用户id找到对应的购物车
            cartCriteria.andUserIdEqualTo(userId);
            cartCriteria.andCheckedEqualTo(true);
            checkedGoodsList = cartMapper.selectByExample(cartExample);
        } else {
            Cart cart = cartMapper.selectByPrimaryKey(cartId);
            checkedGoodsList.add(cart);
        }

        BigDecimal checkedGoodsAmount = new BigDecimal("0");
        for (Cart goods : checkedGoodsList) {
            //总金额
            //先得出数量的bd类型
            String numberShort1 = String.valueOf(goods.getNumber());
            BigDecimal numberBigDecimal1 = new BigDecimal(numberShort1);

            //再算出该商品总价的bd类型（乘法）
            BigDecimal amountBigDecimal1 = goods.getPrice().multiply(numberBigDecimal1);

            checkedGoodsAmount = amountBigDecimal1.add(checkedGoodsAmount);
        }

        BigDecimal freightPrice;

        //TODO 这里要读配置文件
        Properties properties = new Properties();
        try {
            FileInputStream fileInputStream = new FileInputStream(new File("src/main/resources/config.properties"));
            properties.load(fileInputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String market_express_freight_min = properties.getProperty("market_express_freight_min");
        String market_express_freight_value = properties.getProperty("market_express_freight_value");
        if (checkedGoodsAmount.compareTo(new BigDecimal(market_express_freight_min)) > -1) {
            freightPrice = new BigDecimal("0");
        } else {
            freightPrice = new BigDecimal(market_express_freight_value);
        }


        BigDecimal goodsTotalPrice = new BigDecimal("0").add(checkedGoodsAmount).add(freightPrice);

        BigDecimal actualPrice = goodsTotalPrice.subtract(couponPrice);

        BigDecimal orderTotalPrice = new BigDecimal("0").add(actualPrice);


        //填充
        CheckoutVO checkoutVO = new CheckoutVO();
        checkoutVO.setActualPrice(actualPrice);
        checkoutVO.setAddressId(addressId);
        checkoutVO.setAvailableCouponLength(availableCouponLength);
        checkoutVO.setCartId(cartId);
        checkoutVO.setCheckedAddress(address);
        checkoutVO.setCheckedGoodsList(checkedGoodsList);
        checkoutVO.setCouponId(couponId);
        checkoutVO.setCouponPrice(couponPrice);
        checkoutVO.setFreightPrice(freightPrice);
        checkoutVO.setGoodsTotalPrice(goodsTotalPrice);
        checkoutVO.setGrouponPrice(grouponPrice);
        checkoutVO.setGrouponRulesId(grouponRulesId);
        checkoutVO.setOrderTotalPrice(orderTotalPrice);
        checkoutVO.setUserCouponId(userCouponId);

        return checkoutVO;
    }


}
